<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Homeuser;
use App\Models\Homedetails;
use DB;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Hash;
use Illuminate\Support\Facades\Validator;
use PhpSpec\Listener\RerunListener;
use App\Http\Requests\Dohomeemail;
class UsersettingsController extends CommonController
{
    /**
     * 头像设置
     */
     public function photos()
    {
        $id = session('login');
        $userinfo = DB::table("zy_userdetails")->where("uid",$id)->first();
         // 加载账户设置
        return view('home.usersettings.photos',compact("userinfo"),['title'=>'头像设置']);
    }

    /**
     * 接受头像传输数据
     */
    public function dophotos(Request $request)
    {
         $id = session('login');
        $file = $request->file('photo');

        $diskpath = "uploads/".date("Ymd");
            //判断文件是否上传成功
        if($file && $file->isValid()){
            //获取原文件名
            $originalName = $file->getClientOriginalName();
            //扩展名
            $ext = $file->getClientOriginalExtension();
            //文件类型
            $type = $file->getClientMimeType();
            //临时绝对路径
            $realPath = $file->getRealPath();


            $filename = date('Y-m-d-H-i-S').'-'.uniqid().'.'.$ext;
            $bool = $file->move($diskpath,$filename);
            $avatarimg = "/".$diskpath."/".$filename;
            $avatarimgarr['photo'] = $avatarimg;
            $upuserres = DB::table("zy_userdetails")->where("uid",$id)->update($avatarimgarr);
            if($upuserres!==false)
            {
                return redirect('home/usersettings/index');
            }else{
                return back()->with('errors','上传失败');
            }

        }else{
            return back()->with('errors','上传失败');
        }
        // return response()->json(['ServerNo' => '200','ResultData' => $fileName]);
    }


    private function checkFile($file)
    {
        if (!$file->isValid()) {
            return ['status' => false, 'msg' => '文件上传失败'];
        }

        if ($file->getClientSize() > $file->getMaxFilesize()) {
            return ['status' => false, 'msg' => '文件大小不能大于2M'];
        }

        return ['status' => true];
    }
    /**
     * 账户设置
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
         $id = session('login');
         $userinfo = DB::table("zy_userdetails")
            ->leftJoin('zy_user', 'zy_userdetails.uid', '=', 'zy_user.id')
            ->where('uid', $id)
            ->first();

         // 加载账户设置
        return view('home.usersettings.index',compact('userinfo'),['title'=>'账户设置']);
    }

    /**
     * 基本设置
     *
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
         $id = session('login');
        $userinfo = DB::table("zy_userdetails")
            ->leftJoin('zy_user', 'zy_userdetails.uid', '=', 'zy_user.id')
            ->where('uid', $id)
            ->first();
        //返回修改页面
         return view('home.usersettings.edit',compact('userinfo'),['title'=>'账户设置']);
    }

     /**
     * 基本设置--数据接受
     *
     * @return \Illuminate\Http\Response
     */
    public function doedit(Request $request)
    {
         $id = session('login');
        //获取用户输入的值
         $input = Input::except('_token');

         // 输入数据是否符合表单验证规则
        $rule = [
            'nickname'=>'required|between:2,12',
            'age'=>'required|numeric',
            'sex'=>'required',
            'email' => 'required',
        ];
        $mess = [
            'nickname.required' => '昵称必须输入',
            'nickname.between'  => '用户名长度在2-12之间',
            'age.required'  => '年龄必须输入',
            'age.numeric'  => '请输入有效数字',
            'sex.required'  => '性别必须输入',
            'email.required' => '邮箱必须输入',
        ];
        $validator = Validator::make($input,$rule,$mess);
         // 如果验证失败
        if($validator->fails()){
            return back()
                ->withErrors($validator)
                ->withInput();
    }
    $userdata['age'] = $input['age'];
    $userdata['email'] = $input['email'];
    $userdata['nickname'] = $input['nickname'];
    $userdata['sex'] = $input['sex'];
    $userdata['description'] = $input['description'];

    $data = DB::table("zy_userdetails")
            ->leftJoin('zy_user', 'zy_userdetails.uid', '=', 'zy_user.id')
            ->where('uid', $id)->update($userdata);

    // $re =  Homeuser::create($input);
    //添加成功
    if($data!==false)
    {
        return redirect('home/usersettings/index');
    }else{
        return back()->with('errors','用户添加失败');
    }

}


     /**
     * 账户安全
     *
     * @return \Illuminate\Http\Response
     */
    public function security()
    {
         return view('home.usersettings.security',['title'=>'账户安全']);
    }

    /**
     * 用户密码修改
     *
     * @return \Illuminate\Http\Response
     */
    public function userpass()
    {

         return view('home.usersecurity.userpass',['title'=>'密码修改']);
    }

    // 验证码生成
    public function captcha($tmp)
    {

        $phrase = new PhraseBuilder;
        // 设置验证码位数
        $code = $phrase->build(4);
        // 生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder($code, $phrase);
        // 设置背景颜色
        $builder->setBackgroundColor(220, 210, 230);
        $builder->setMaxAngle(25);
        $builder->setMaxBehindLines(0);
        $builder->setMaxFrontLines(0);
        // 可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        // 获取验证码的内容
        $phrase = $builder->getPhrase();
        // 把内容存入session
        \Session::flash('code', $phrase);
        // 生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header("Content-Type:image/jpeg");
        $builder->output();


    }

    /**
     * 用户密码修改--第二步
     *
     * @return \Illuminate\Http\Response
     */
    public function passedit(Request $request)
    {
         //获取浏览器提交的数据
        $data=$request->all();
        //获取当前登录用户
        $username=session('username');
        $user = DB::table('zy_user')->where('username','=',$username)->first();
        //判断新密码与确认密码是否相等
        if($data['new_password']!=$data['re_password'])
        {
            echo "<script>alert('两次密码输入不一致');location.href='/home/usersecurity/userpass'</script>";
        }

        if(Hash::check($data['old_password'], $user['password'])){

           $password=Hash::make($data['new_password']);
           //获取当前用户id
           $id=session('login');
           $res=DB::table('zy_user')->where('id',$id)->update(['password'=>$password]);
               if($res)
               {

                // return redirect('/home/usersettings/index')->with('success','密码修改成功');
                echo "<script>alert('密码修改成功');location.href='/home/usersettings/index'</script>";
               }else{
                 echo "<script>alert('密码修改失败');location.href='/home/usersecurity/userpass'</script>";
               }


        }else{

            return back()->with('error','密码修改失败');
        }




        //      如果正确跳转后跳转到首页，如果不正确返回
        // return redirect('home.usersecurity.passedit');
         // return view('home.usersecurity.passedit',['title'=>'密码修改']);
    }


    /**
     * 用户手机号修改
     *
     * @return \Illuminate\Http\Response
     */
    public function userphone()
    {
         return view('home.usersecurity.userphone',['title'=>'手机号修改']);
    }
    /**
     * 用户手机号修改--第二步
     *
     * @return \Illuminate\Http\Response
     */
    public function do_phone_edit(Request $request)
    {
        $id=session('login');
         $data=$request->all();
         $res=DB::table('zy_user')->where('id',$id)->update(['phone'=>$data['phone']]);
         if($res)
           {
            // return redirect('/home/usersettings/index')->with('success','手机号修改成功');
            echo "<script>alert('手机号修改成功');location.href='/home/usersettings/index'</script>";
           }else{
            echo "<script>alert('手机号修改失败');location.href='/home/usersecurity/userphone'</script>";
           }
    }


    /**
     * 用户邮箱修改
     *
     * @return \Illuminate\Http\Response
     */
    public function useremail()
    {
         return view('home.usersecurity.useremail',['title'=>'邮箱修改']);
    }

    /**
     * 用户邮箱修改
     *
     * @return \Illuminate\Http\Response
     */
    public function emailedit(Dohomeemail $request)
    {
        $id=session('login');
         $data=$request->all();
         $res=DB::table('zy_user')->where('id',$id)->update(['email'=>$data['email']]);
         if($res)
           {
            // return redirect('/home/usersettings/index')->with('success','邮箱修改成功');
             echo "<script>alert('邮箱修改成功');location.href='/home/usersettings/index'</script>";
           }else{
            echo "<script>alert('邮箱修改失败');location.href='/home/usersecurity/useremail'</script>";
           }
    }
}
